class BrowserHelper {
	static bodyDom: any = document.body;

	static fixScroll = (fixed: boolean) => {
		if (fixed) {
			BrowserHelper.bodyDom.style.overflow = 'hidden';
		} else {
			BrowserHelper.bodyDom.style.overflow = 'auto';
		}
	};
	static scroll(x = 0, y = 0) {
		window.scrollTo(x, y);
	}
	static eleScroll(ele, x = 0, y = 0) {
		if (ele.scrollTo) {
			ele.scrollTo(x, y);
		} else {
			ele.scrollTop = 0;
		}
	}
	static scrollToElement(ele) {
		if (ele.scrollIntoView) {
			ele.scrollIntoView({
				behavior: 'smooth',
			});
		} else {
			window.scrollTo(0, ele.offsetTop);
		}
	}
	static getDpr() {
		let dpr = 1;
		if (window.devicePixelRatio) {
			dpr = window.devicePixelRatio;
		}
		if (dpr > 3) dpr = 3;
		return dpr;
	}

	static loadScript<T>(id: string, src: string, isAsync = true, isDefer = true): Promise<T> {
		const dom = document.querySelector(`#${id}`);
		return new Promise((resolve, reject) => {
			if (dom == null) {
				const ele = document.createElement('script');
				ele.id = `${id}`;
				ele.src = src;
				if (isAsync) {
					ele.async = true;
				}
				if (isDefer) {
					ele.defer = true;
				}

				ele.addEventListener(
					'load',
					() => {
						resolve(undefined);
					},
					{ once: true },
				);

				ele.addEventListener(
					'error',
					(err) => {
						reject(err);
					},
					{ once: true },
				);
				document.body.appendChild(ele);
			} else {
				resolve(undefined);
			}
		});
	}
}

export default BrowserHelper;
